package com.saver.modules.sys.service;

import com.saver.common.utils.IPUtils;
import com.saver.common.utils.R;
import com.saver.modules.sys.dao.SysLoginLogDao;
import com.saver.modules.sys.dao.SysParamDao;
import com.saver.modules.sys.dao.SysUserDao;
import com.saver.modules.sys.entity.SysLoginLogEntity;
import com.saver.modules.sys.entity.SysParamEntity;
import com.saver.modules.sys.entity.SysUserEntity;
import com.saver.modules.sys.form.SysLoginForm;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import nl.bitwalker.useragentutils.Version;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SysLoginService {

    @Autowired
    private SysCaptchaService sysCaptchaService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    private MailService mailService;

    @Autowired
    private SysParamDao sysParamDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysLoginLogDao sysLoginLogDao;


    public Integer getCurrentDayLoginCount(){
        Date date = new Date();
        date.setSeconds(0);
        date.setMinutes(0);
        date.setHours(0);
        return sysLoginLogDao.countAllByCreateDateAfter(date);
    }

    public Integer getAllLoginCount(){
        return sysLoginLogDao.countAllByIsSuccess(true);
    }

    public Map<String, Object> login(SysLoginForm form, HttpServletRequest request) {
        SysLoginLogEntity entity = new SysLoginLogEntity();
        entity.setUsername(form.getUsername());
        entity.setCreateDate(new Date());
        String ipAddr = IPUtils.getIpAddr(request);
        entity.setIp(ipAddr);

        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        Browser browser = userAgent.getBrowser();
        Version browserVersion = userAgent.getBrowserVersion();
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();

        entity.setBrowser(browser.getName());
        entity.setMonitorSystem(operatingSystem.getName());
        entity.setBrowserVersion(browserVersion.getVersion());
        entity.setAddress(form.getAddress());
        SysParamEntity login_captcha_check = sysParamDao.findByParamName("LOGIN_CAPTCHA_CHECK");

        if ("Y".equals(login_captcha_check.getParamValue())) {

            boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
            if (!captcha) {
                entity.setSuccess(false);
                entity.setMsg("验证码不正确");
                sysLoginLogDao.save(entity);
                return R.error("验证码不正确");
            }
        }

        //用户信息
        SysUserEntity user = sysUserDao.findByUsername(form.getUsername());

        //账号不存在、密码错误
        if (user == null) {
            entity.setSuccess(false);
            entity.setMsg("账号不存在");
            sysLoginLogDao.save(entity);
            return R.error("账号不存在");
        } else if (!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt(), 10).toHex())) {
            entity.setSuccess(false);
            entity.setMsg("密码不正确");
            sysLoginLogDao.save(entity);
            return R.error("密码不正确");
        } else if (user.getStatus() == 0) {
            //账号锁定
            entity.setSuccess(false);
            entity.setMsg("账号已被锁定");
            sysLoginLogDao.save(entity);
            return R.error("账号已被锁定,请联系管理员");
        }
//        SysParamEntity login_email_remind = sysParamDao.findByParamName("LOGIN_EMAIL_REMIND");
//        String email = user.getEmail();
//        if ("Y".equals(login_email_remind.getParamValue()) && email != null && !"".equals(email)) {
//            new Thread(() -> {
//                Map<String, String> map = new HashMap<>();
//                map.put("${user}", user.getName());
//                mailService.sendHtmlTemplateMain("hint-login.html", map, email, "fast系统登录提醒");
//            }).start();
//        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());
        entity.setSuccess(true);
        entity.setMsg("登录成功");

        sysLoginLogDao.save(entity);
        return r;
    }
}
